<template>
  <div>
    <el-card style="min-width: 320px;">
      <div style="height: 260px; overflow-y: auto; margin-bottom: 12px;">
        <div v-for="(msg, idx) in messages" :key="idx" :style="{ textAlign: msg.role === 'user' ? 'right' : 'left', margin: '8px 0' }">
          <el-tag v-if="msg.role === 'user'" type="primary">你：</el-tag>
          <el-tag v-else type="success">客服小王：</el-tag>
          <span style="margin-left: 8px;">{{ msg.content }}</span>
        </div>
      </div>
      <el-input
        v-model="input"
        placeholder="请输入你的问题..."
        @keyup.enter="send"
        :disabled="loading"
        clearable
      />
      <el-button type="primary" @click="send" :loading="loading" style="margin-top: 8px; width: 100%;">发送</el-button>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'

interface Message {
  role: 'user' | 'ai';
  content: string;
}

const input = ref('')
const loading = ref(false)
const messages = ref<Message[]>([
  { role: 'ai', content: '你好，我是AI助手，有什么可以帮您？' }
])

const API_KEY = 'sk-c897b0bd30b54e5c9d30276eb31ec537' // 你的deepseek key
const API_URL = 'https://api.deepseek.com/v1/chat/completions'
async function send() {
  if (!input.value.trim()) return
  messages.value.push({ role: 'user', content: input.value })
  const userInput = input.value
  input.value = ''
  loading.value = true

  try {
    // 构造符合deepseek规则的messages
    const history = messages.value.map(m => ({
      role: m.role === 'ai' ? 'assistant' : m.role,
      content: m.content
    }))
    // 追加本次用户输入
    history.push({ role: 'user', content: userInput })
    const res = await axios.post(
      API_URL,
      {
        model: 'deepseek-chat',
        messages: [
          { role: 'system', content: '你是一个有帮助的AI助手。' },
          ...history
        ],
        temperature: 1,
        max_tokens: 1024
      },
      {
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json'
        }
      }
    )
    const aiReply = res.data.choices[0].message.content
      messages.value.push({ role: 'ai', content: aiReply })
  } catch (error) {
    console.error(error)
    messages.value.push({ role: 'ai', content: 'AI助手出现错误，请稍后再试。' })
  } finally {
    loading.value = false
  }
}
</script> 